package com.dut.bbs.activity;

import android.R.integer;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.dut.bbs.R;
import com.dut.bbs.adapter.ThreadAdapter;
import com.dut.bbs.data.ThreadDetail;
import com.dut.bbs.data.UserInfo;
import com.dut.bbs.entity.LoginEntity;
import com.dut.bbs.util.Dg;
import com.dut.bbs.util.NetWorkAvailable;
import com.dut.bbs.util.Settings;
import com.dut.bbs.util.StringUtils;
import com.dut.bbs.util.URLConstant;
import com.dut.bbs.web.HtmlSource;

/**
 * @author weipeng
 * 贴子页
 */
public class ThreadActivity extends BaseActivity {
	private ListView lv_threadlist;
	private Context context;
	private String thread_url;
	private int currentPage; //当前页数
	private int maxPage;    //最大页数
	public static final int next_menu_ID = Menu.FIRST+1;
    public static final int pre_menu_ID = Menu.FIRST+2;
    public static final int tag_menu_ID = Menu.FIRST;
    public static final int reply_menu_ID = Menu.FIRST+3;
    private LinearLayout pop;
    private Button bt_next,bt_prev,bt_tag,bt_reply;
    private String board;
    static int ifBar=0;
    private Handler handler = new Handler() {  
    	@Override  
        public void handleMessage(Message msg) {
    		switch(msg.what){
    			case 1:
    				((BaseAdapter) lv_threadlist.getAdapter()).notifyDataSetChanged();
    				break;
    			case 2:
    				AlertDialog.Builder builder = new Builder(context);
    				builder.setMessage(msg.getData().getString("info"));
    				final Bundle b = msg.getData();
    				builder.setPositiveButton("私信TA", new DialogInterface.OnClickListener() {
    					
    					@Override
    					public void onClick(DialogInterface dialog, int which) {
    						if (!LoginEntity.isLogin()) {
    							AlertDialog.Builder builder = new Builder(context);
    							builder.setMessage("亲，你还没登录呢");
    							builder.setTitle("提示");
    							builder.setIcon(android.R.drawable.ic_dialog_alert);
    							builder.setPositiveButton("去登录",
    									new DialogInterface.OnClickListener() {
    										public void onClick(DialogInterface dialog,
    												int which) {
    											dialog.dismiss();
    											Intent intent = new Intent(context,LoginActivity.class);
    											Bundle bundle = new Bundle();
    											bundle.putString("fromItem", "1");
    											intent.putExtras(bundle);
    											context.startActivity(intent);
    										}

    									});
    							builder.setNegativeButton(
    									"算了吧",
    									new android.content.DialogInterface.OnClickListener() {
    										public void onClick(DialogInterface dialog,
    												int which) {
    											dialog.dismiss();
    										}
    									});
    							builder.create().show();
    						}else{
    							Intent intent = new Intent(context,PostActivity.class);
    							intent.putExtras(b);
    							startActivity(intent);
    						}
    					}
    				});
    				builder.create().show();
    				getProgressDialog().dismiss();
    				break;
    			case 3:
    				Dg.showToast(context, "外网不能回复哦，亲");
    				getProgressDialog().dismiss();
    				break;
    			case 4:
    				Bundle bundle = msg.getData();
    				Intent intent = new Intent(context,PostActivity.class);
					intent.putExtras(bundle);
					startActivity(intent);
					getProgressDialog().dismiss();
					break;
    		}
    	}
    };
    
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);	
		setContentView(R.layout.thread);
		context = this;
		// 获取贴子页url
		thread_url = URLConstant.URL_BASE + getIntent().getStringExtra("url");
		board = StringUtils.getBoard(thread_url);
		lv_threadlist = (ListView) findViewById(R.id.lv_threadlist);
		TextView tv_title = (TextView) findViewById(R.id.activitytitle);
		tv_title.setText(board+"- "+getIntent().getStringExtra("title"));
		lv_threadlist.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				
			}
		});
		initPopupWindow();
		setupViews();
		HtmlSourseGeter h = new HtmlSourseGeter(context);
		h.execute(thread_url);
	}
	
	//异步加载页面的类
	class HtmlSourseGeter extends AsyncTask<String, integer, String>
    {

        private Context context;
        public HtmlSourseGeter(Context context)
        {
            this.context = context;
        }

        @Override
        protected String doInBackground(String... params)
        {
            String result = null;
            try
            {
                result = HtmlSource.getHtml_data(params[0]);
            } catch (Exception e)
            {
            }
            try{
            	currentPage = Integer.parseInt(result.split("页</a>\\|<a class=\"plant\">")[1].split("/")[0]);
            	maxPage = Integer.parseInt(result.split("页</a>\\|<a class=\"plant\">")[1].split("/")[1].split("<")[0]);
            }catch(Exception e){
            	currentPage=1;
            	maxPage=1;
            }
            return result;
        }

        @Override
        protected void onPreExecute()
        {
        	getProgressDialog().setMessage("抓取页面中...");
            getProgressDialog().show();
        }

        @Override
        protected void onPostExecute(String str)
        {

            String date = str;

            if (date == null)
            {
                Dg.showToast(context, "抓取页面失败！");
                getProgressDialog().dismiss();
                return;
            }
            try{
            	ThreadAdapter adapter = new ThreadAdapter(context, ThreadDetail.getTextDetail(date,thread_url),handler,getProgressDialog());
                lv_threadlist.setAdapter(adapter);
                getProgressDialog().dismiss();
            }catch(Exception e){
            	getProgressDialog().dismiss();
            	Dg.showToast(context, "文章已被删除或链接错误！");
            }                     
        }

    }
//	public boolean onCreateOptionsMenu(Menu menu){
//		super.onCreateOptionsMenu(menu);
//		menu.add(0, next_menu_ID, 0, "下一页").setIcon(R.drawable.next);
//		menu.add(0, pre_menu_ID, 0, "上一页").setIcon(R.drawable.prev);
//		menu.add(0, tag_menu_ID,0,"操作").setIcon(R.drawable.tag);
//		menu.add(0, reply_menu_ID,0,"回复").setIcon(R.drawable.huifu);
//		return true;
//	}
//    public boolean onOptionsItemSelected(MenuItem item){
//		switch(item.getItemId()){
//		case next_menu_ID:
//			currentPage++;
//			HtmlSourseGeter h1 = new HtmlSourseGeter(this);
//			h1.execute(thread_url+"?p="+currentPage);
//			break;
//		case pre_menu_ID:
//			currentPage--;
//			HtmlSourseGeter h2 = new HtmlSourseGeter(this);
//			h2.execute(thread_url+"?p="+currentPage);
//			break;
//		case reply_menu_ID:
//			Intent in = new Intent(context,PostActivity.class);
//			Bundle bundle = new Bundle();
//			bundle.putString("url", ThreadDetail.getReplyURL(thread_url));
//			bundle.putString("title", "");
//			in.putExtras(bundle); 
//			startActivity(in);
//		}
//		return true;
//    }
//    public boolean onMenuOpened(int featureId, Menu menu){
//    	menu.findItem(pre_menu_ID).setEnabled(true);
//    	menu.findItem(next_menu_ID).setEnabled(true);
//    	if(currentPage==1)
//			menu.findItem(pre_menu_ID).setEnabled(false);
//		if(currentPage==maxPage)
//			menu.findItem(next_menu_ID).setEnabled(false);
//		if(!LoginEntity.isLogin())
//			menu.findItem(reply_menu_ID).setEnabled(false);
//		return super.onMenuOpened(featureId, menu);
//    }
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	if(keyCode == KeyEvent.KEYCODE_MENU){
    		if(pop.getVisibility() != View.VISIBLE){
    			pop.setVisibility(View.VISIBLE);
    			ifBar = 1;
    		}else{
    			pop.setVisibility(View.GONE);
    			ifBar = 0;
    		}
    		return true;
    	}else{
    		return super.onKeyDown(keyCode, event);
    	}
    }
    private void initPopupWindow(){
    	pop = (LinearLayout) findViewById(R.id.ll_popmenu);
    	if("2".equals(Settings.showBar)){
    		if(pop.getVisibility() != View.VISIBLE){
    			pop.setVisibility(View.VISIBLE);
    			ifBar = 1;
    		}
    	}else if("1".equals(Settings.showBar)){
    		if(pop.getVisibility() != View.GONE){
    			pop.setVisibility(View.GONE);
    			ifBar = 0;
    		}
    	}else{
    		if(1==ifBar)
    			pop.setVisibility(View.VISIBLE);
    		else
    			pop.setVisibility(View.GONE);
    	}
    	bt_next = (Button) findViewById(R.id.btn_next);
    	bt_prev = (Button) findViewById(R.id.btn_prev);
    	bt_tag = (Button) findViewById(R.id.btn_tag);
    	bt_reply = (Button) findViewById(R.id.btn_reply);
    }
    private void setupViews(){
    	bt_next.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				if(currentPage==maxPage)
					Dg.showToast(context, "已经是最后一页了");
				else{
					currentPage++;
					HtmlSourseGeter h1 = new HtmlSourseGeter(context);
					h1.execute(thread_url+"?p="+currentPage);
				}
			}
		});
    	bt_prev.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(currentPage==1)
					Dg.showToast(context, "已经是第一页了");
				else{
					currentPage--;
					HtmlSourseGeter h2 = new HtmlSourseGeter(context);
					h2.execute(thread_url+"?p="+currentPage);
				}
			}
		});
    	bt_reply.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(!LoginEntity.isLogin()){
					AlertDialog.Builder builder = new Builder(context);
					builder.setMessage("亲，你还没登录呢");
					builder.setTitle("提示");
					builder.setIcon(android.R.drawable.ic_dialog_alert);
					builder.setPositiveButton("去登录",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
									Intent intent = new Intent(context,LoginActivity.class);
									Bundle bundle = new Bundle();
									bundle.putString("fromItem", "1");
									intent.putExtras(bundle);
									context.startActivity(intent);
								}

							});
					builder.setNegativeButton(
							"算了吧",
							new android.content.DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
								}
							});
					builder.create().show();
				}else if(!NetWorkAvailable.goodNetIp()){
					Dg.showToast(context, "外网不能回复哦，亲");
				}else{
					Intent in = new Intent(context,PostActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString("url", StringUtils.getReplyURL(thread_url));
					bundle.putString("title", "");
					bundle.putInt("flag", 2);
					in.putExtras(bundle); 
					startActivity(in);
				}
			}
		});
    	bt_tag.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				String[] items = {"刷新该主题","访问该讨论区","跳转到主题某一页"};
				AlertDialog.Builder builder = new Builder(context);
				builder.setTitle("选择操作");
				builder.setItems(items, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if(which==1){
							Intent in = new Intent(context,ArticleActivity.class);
							Bundle bundle = new Bundle();
							bundle.putString("board", board);
							in.putExtras(bundle);
							startActivity(in);
						}else if(which==2){
							AlertDialog.Builder bd = new Builder(context);
							String[] listItems = new String[maxPage];
							for(int i=1;i<=maxPage;i++){
								listItems[i-1] = "第"+i+"页";
							}
							bd.setTitle("选择页数").setItems(listItems, new DialogInterface.OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int which) {
									HtmlSourseGeter h1 = new HtmlSourseGeter(context);
									h1.execute(thread_url+"?p="+(which+1));
								}
							});
							bd.create().show();
						}else{
							HtmlSourseGeter h1 = new HtmlSourseGeter(context);
							h1.execute(thread_url);
						}
					}
				});
				builder.create().show();
			}
		});
    }
}
